<?php

// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace plugins\pay_zhl;//Demo插件英文名，改成你的插件英文就行了
use cmf\lib\Plugin;
require_once PLUGINS_PATH."pay_zhl/wechat/lib/WxPay.Api.php";
require_once PLUGINS_PATH."pay_zhl/wechat/lib/WxPay.Notify.php";
require_once PLUGINS_PATH."pay_zhl/wechat/WxPay.JsApiPay.php";


/**
 * WechatZhlPlugin
 */
class PayZhlPlugin extends Plugin
{

    public $info = [
        'name'        => 'PayZhl',
        'title'       => '第三方支付',
        'description' => '第三方支付',
        'status'      => 1,
        'author'      => 'zhl',
        'version'     => '1.0'
    ];

    public $hasAdmin = 1;//插件是否有后台管理界面

    // 插件安装
    public function install()
    {
        return true;//安装成功返回true，失败false
    }

    // 插件卸载
    public function uninstall()
    {
        return true;//卸载成功返回true，失败false
    }

    //实现的wechatpay钩子方法-微信支付
    public function wechatpay($param)
    {
        ini_set('date.timezone','Asia/Shanghai');

        $wechat_pay = cmf_get_option('wechat_pay');
	
        //①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($param['Body']);//商品描述
        $input->SetAttach($param['Attach']);//附加数据,作为自定义参数使用。
        $input->SetOut_trade_no($param['Out_trade_no']);//作为自定义参数使用。
        $input->SetTotal_fee($param['Total_fee']*100);//标价金额
        $input->SetTime_start(date("YmdHis"));//交易起始时间
        $input->SetTime_expire(date("YmdHis", time() + 600));//交易结束时间
        $input->SetNotify_url($wechat_pay['Notify_url']);//通知地址,异步接收微信支付结果通知的回调地址
        $input->SetTrade_type("JSAPI");//交易类型
        $input->SetOpenid($openId);//用户openid
        $order = \WxPayApi::unifiedOrder($input);
	
        $jsApiParameters = $tools->GetJsApiParameters($order);
        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $this->assign('jsApiParameters',$jsApiParameters);
        $this->assign('editAddress',$editAddress);
        $this->assign('param',$param);
        echo  $this->fetch("widget");

    }

    //实现的wechatnotify钩子方法-微信回调
    public function wechatnotify($param){  
        //如果返回成功则验证签名
        try {
            $result = \WxPayResults::Init($param);         
        } catch (\WxPayException $e){
            $msg = $e->errorMessage();
            file_put_contents('log/log.txt',var_export($msg,true),FILE_APPEND);
            return false;
        }

        $msg = "OK";       
        if(!array_key_exists("transaction_id", $result)){
            $msg = "输入参数不正确";
           file_put_contents('log/log.txt',var_export($msg,true),FILE_APPEND);
            return false;
        }
      
        //查询订单，判断订单真实性
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($result["transaction_id"]);  
        $result = \WxPayApi::orderQuery($input);   
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {

       		update_order_status($result["out_trade_no"], $result["transaction_id"],'WEIXIN');
          	echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');           
        }else{
            $msg = "订单查询失败";
            file_put_contents('log/log.txt',var_export($msg,true),FILE_APPEND);
            return false;
        }
     }
//微信退款
     public function refundweixin($param){
         $transaction_id = $param["transaction_id"];
         $total_fee = $param["total_fee"]*100;
         $refund_fee = $param["refund_fee"]*100;
         $wechat_pay = cmf_get_option('wechat_pay');
         $input = new \WxPayRefund();
         $input->SetTransaction_id($transaction_id);
         $input->SetTotal_fee($total_fee);
         $input->SetRefund_fee($refund_fee);
         $input->SetOut_refund_no($param['return_order_no']);
         $input->SetOp_user_id($wechat_pay['MCHID']);
      
         $res=\WxPayApi::refund($input);
       
         return $res;
     }




}